#include <cstdio>
#include <sys/socket.h>
#include <string.h>
#include <unistd.h>
#include <errs.h>
#include <arpa/inet.h>


#define BUFFER_SIZE 1024

int my_getline(char* line, int max_size)
{
	int c;
	int len = 0;
	while( (c = getchar()) != EOF && len < max_size ){
		if('\n' == c)
			break;
        line[len++] = c;
	}
	line[len] = '\0';
	return len;
}

int main(int argc, char const *argv[])
{
    sockaddr_in server_addr;
    bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(8888);
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    errif(sockfd == -1, "client socket create fail.");
    int ret = connect(sockfd, (sockaddr*)&server_addr, sizeof(sockaddr));
    errif(ret == -1, "client connect fail.");
    while (true)
    {
        char buf[BUFFER_SIZE];
        size_t len = 0;
        bzero(&buf, sizeof(buf));
        my_getline(buf, BUFFER_SIZE);
        ssize_t write_bytes = write(sockfd, buf, sizeof(buf));
        if (write_bytes == -1) {
            printf("Server disconnected...\n");
            break;
        }
        bzero(&buf, sizeof(buf));
        ssize_t read_bytes = read(sockfd, buf, sizeof(buf));
        if (read_bytes > 0) {
            printf("Receive message: %s...\n", buf);
        }else if (read_bytes == 0) {
            printf("Server disconnected...\n");
            break;
        }else if (read_bytes < 0) {
            close(sockfd);
            errif(true, "socket read error...\n");
        }
    }
    
    close(sockfd);
    return 0;
}
